#!/usr/bin/python
# -*-coding:utf-8-*-
import pymysql
from PIL import Image, ImageDraw, ImageFont

"""
批量生成学生照片
batch_generate_student_pic
"""


def generate_student_pic(school_id, study_section, grade_number, class_number, student_name, id_number):
    # python创建图片，并且添加文字
    im = Image.new("RGB", (154, 189), 'white')
    # 创建一个Image对象,width=154,height=189,背景为白色
    draw = ImageDraw.Draw(im)  # 创建一个绘画对象
    fnt = ImageFont.truetype(r'C:\Windows\Fonts\STXINGKA.TTF', 26)
    # 生成一个font对象,第一个参数为字体路径，第二个为字体大小
    draw.text((10, 40), str(school_id), fill='black', font=fnt)
    draw.text((0, 80), '%s%s级%s班' % (study_section, grade_number, class_number), fill='black', font=fnt)
    draw.text((20, 120), student_name, fill='black', font=fnt)
    # 向图片上写入文字,第一个参数为字在图片上的起始坐标,第二个为内容。
    # im.show()  # 调用默认图片查看器查看
    if id_number != None and id_number != '':
        filename = id_number
    else:
        filename = '%s_%s%s级%s班_%s' % (school_id, study_section, grade_number, class_number, student_name)
    # 保存为一个.jpg文件
    im.save(r'H:\test\3134000027\初中2019级2班\%s.jpg' % filename)


if __name__ == "__main__":
    # 获取数据连接
    connection = pymysql.connect(host="127.0.0.1", user="root", password="root", db="ems", charset="utf8mb4")
    try:
        # 获取会话指针
        with connection.cursor() as cursor:
            # 创建sql语句
            sql = "SELECT school_id,study_section,grade_number,class_number,student_name,id_number " \
                  "FROM `examination_student_info`  WHERE `examination_id`=249341757785088" \
                  " AND school_id=3134000027 AND grade_number=2019 AND class_number=2"
            # 执行sql语句
            cursor.execute(sql)
            # 获取所有记录列表
            results = cursor.fetchall()
    finally:
        connection.close()
    for row in results:
        school_id = row[0]
        study_section = row[1]
        grade_number = row[2]
        class_number = row[3]
        student_name = row[4]
        id_number = row[5]
        generate_student_pic(school_id, study_section, grade_number, class_number, student_name, id_number)
        print("生成图片：" + str(row))
